﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using  VAdvantage.Controls;
using System.Windows.Data;
using System.ComponentModel;
using VAdvantage.Classes;
using VAdvantage.Model;
using VAdvantage.Utility;

namespace VAdvantage.Grids
{
    public class VDataGridTextButtonColumn :DataGridBoundColumn, IDataGridColumn, IDataGridSpecialCaseColumn
    {
        #region

        private GridField _field;
        private Lookup _lookup = null;

        private VTextBoxButton editingControl = null;
        private TextBlock hostTextBlock = null;
        private TextBox hostTextBox = null;
        private object currentCellValue = null;
        private int _displayType;

        private String _columnName;
        ValueToTextConverter conveter = null;


        #endregion

        #region Property

        public string DataPropertyName
        {
            get
            {
                return _columnName;
            }
            set
            {
                _columnName = value.ToUpper();
                SetBinding();
            }
        }

        private void SetBinding()
        {
            this.Binding = new Binding(_columnName);
            conveter = new ValueToTextConverter();
            if (_field != null)
            {
                conveter.DataSource = _field.GetLookup();
            }
            this.Binding.Converter = conveter;

        }

        public Controls.VDataGrid DataGridView
        {
            get;
            set;
        }

        public GridField    Field
        {
            get
            {
                return _field;
            }
            set
            {
                _field = value;
                if (_field != null)
                {
                    editingControl = new VTextBoxButton(_field.GetColumnName(), _field.IsMandatory(false), _field.IsReadOnly(), _field.IsEditable(false), _field.GetDisplayType(), _field.GetLookup());
                    editingControl.SetField(_field);

                    _lookup = _field.GetLookup();

                    _displayType = _field.GetDisplayType();
                    if (conveter != null)
                    {
                        conveter.DataSource = _field.GetLookup();
                    }
                    
                }
            }
        }

        public void Dispose()
        {
            if (editingControl != null)
            {
                editingControl.Dispose();
            }
            editingControl = null;
            if (conveter != null)
            {
                conveter.Dispose();
            }
            conveter = null;
            _field = null;
            hostTextBlock = null;
        }

        public bool ReadOnly
        {

            get;
            set;

        }

        #endregion



        public VDataGridTextButtonColumn()
        {

        }


        protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
        {
            if (editingControl == null)
            {
                editingControl = new VTextBoxButton();
            }
            //editingControl.SelectedValue = cell.

            hostTextBlock = (TextBlock)cell.Content;

            editingControl.SetValueInDataGridColumn(null);

            currentCellValue = ((DataUtil.DataObject)dataItem).GetFieldValue(_columnName);


            //if (cell.Content is TextBlock)
            //{
            //    currentBlock = (TextBlock)cell.Content;
            //}


            return editingControl;
        }

        protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
        {
            //if (editingControl.EditingControlFormOpening)
            //{
            //    editingControl.EditingControlFormOpening = false;
            //    return editingControl;
            //}
            if (cell.Content is VTextBoxButton)
            {
                editingControl.VetoableChangeListener -= new EventHandler(editingControl_VetoableChangeListener);
                currentCellValue = ((VTextBoxButton)cell.Content).GetValue();
                _field.SetValue(currentCellValue);
                ((DataUtil.DataObject)dataItem).SetFieldValue(_columnName, currentCellValue);
                editingControl.SetText("");
                
                return hostTextBlock;
            }

            TextBlock text = Utility.AEnv.GetDataGridElement();

            //TextBox text = new TextBox();
            //text.IsReadOnly = true;
            //text.BorderThickness = new Thickness(0);
            //text.Cursor = Cursors.Arrow;
            //text.IsTabStop = false;

            //text.IsHitTestVisible = t.IsHitTestVisible;
            if (this.Binding != null)
            {
                text.SetBinding(TextBlock.TextProperty, this.Binding);
            }
            return text;
        }

        protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)
        {
           // if (editingEventArgs.OriginalSource is TextBlock)
           // {
                editingControl.EditingControlDataGridView = DataGridView;
                editingControl.SetValueInDataGridColumn(currentCellValue);
                //editingControl.VetoableChangeListener += new EventHandler(editingControl_VetoableChangeListener);
           // }
            return editingElement;
        }

        void editingControl_VetoableChangeListener(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
        }






        public void SetDisplayText(DataGridRow dataGridRow)
        {

           // dataGridRow.co

            object content = this.GetCellContent(dataGridRow);
            if (_lookup == null || !(content is TextBlock))
                return;

            
            object value = null;

            value = ((TextBlock)content).Text;
            if(value.ToString() == "" || value.ToString() =="0")
             {
                 ((TextBlock)content).Text = "Aftereas";
                 return;
             }
             try
             {
                   value = Convert.ToInt32(value);
              }
                catch
                {
                    return;
                }


             BackgroundWorker worker = new BackgroundWorker();
             worker.WorkerSupportsCancellation = true;


             worker.DoWork += (sender, e) =>
             {
                 if (worker.CancellationPending)
                 {
                     e.Cancel = true;
                 }
                 e.Result = value.ToString();

                 if (_displayType == DisplayType.Location)
                 {
                     if (value != null && value.ToString() != "0" && value.ToString() != "")
                     {
                         MLocation locationValue = ((MLocationLookup)_lookup).GetLocation(value, null);
                         if (locationValue == null)
                             e.Result = "<" + value.ToString() + ">";
                         else
                             e.Result = locationValue.ToString();

                     }
                     else
                     {
                         e.Result = "";
                     }
                 }
                 else if (_displayType == DisplayType.Locator)
                 {
                     if (value != null && value.ToString() != "0" && value.ToString() != "")
                     {
                         MLocatorLookup _locator = ((MLocatorLookup)_lookup);

                         _locator.SetOnly_Warehouse_ID(GetOnly_Warehouse_ID());
                         _locator.SetOnly_Product_ID(GetOnly_Product_ID());
                         if (!_locator.IsValid(value))
                         {
                             e.Result = "";
                             return;
                         }
                         e.Result = _locator.GetDisplay(value);
                     }
                     else
                     {
                         e.Result = "";
                     }
                 }
                 else if (_displayType == DisplayType.Search || _field.IsParentColumn())
                 {
                     e.Result = _lookup.GetDisplay(value);
                 }

             };

             worker.RunWorkerCompleted += (sender, e) =>
             {
                 if (!e.Cancelled && !worker.CancellationPending)
                 {
                     ((TextBlock)content).Text = (string)e.Result;
                     ((TextBlock)content).Tag = value;
                 }
             };
             worker.RunWorkerAsync();
            }

        public void SetText(object Id)
        {
            //if (worker != null && worker.IsBusy)
            //{
            //    worker.CancelAsync();
            //    //worker = null;
            //}

           
        }


        #region "Locator"

        /// <summary>
        ///Get Warehouse restriction if any.
        /// </summary>
        /// <returns></returns>
        private int GetOnly_Warehouse_ID()
        {
            Context ctx = Envs.GetContext();
            // gwu: do not restrict locators by warehouse when in Import Inventory Transactions window 
            String AD_Table_ID = ctx.GetContext(_lookup.GetWindowNo(), "0|AD_Table_ID", true);
            if ("572".Equals(AD_Table_ID)) // Import Inventory Transactions
            {
                return 0;
            }

            String only_Warehouse = ctx.GetContext(_lookup.GetWindowNo(), "M_Warehouse_ID", true);
            int only_Warehouse_ID = 0;
            try
            {
                if (only_Warehouse != null && only_Warehouse.Length > 0)
                    only_Warehouse_ID = int.Parse(only_Warehouse);
            }
            catch (Exception ex)
            {
               // log.Log(Logging.Level.SEVERE, ex.Message);
            }
            return only_Warehouse_ID;
        }

        /// <summary>
        ///Get Product restriction if any.
        /// </summary>
        /// <returns></returns>
        private int GetOnly_Product_ID()
        {
            //	if (!Env.isSOTrx(Env.getCtx(), m_WindowNo))
            //		return 0;	//	No product restrictions for PO
            //
            Context ctx = Envs.GetContext();
            // gwu: do not restrict locators by product when in Import Inventory Transactions window 
            String AD_Table_ID = ctx.GetContext(_lookup.GetWindowNo(), "0|AD_Table_ID", true);
            if ("572".Equals(AD_Table_ID)) // Import Inventory Transactions
            {
                return 0;
            }

            String only_Product = ctx.GetContext(_lookup.GetWindowNo(), "M_Product_ID", true);
            int only_Product_ID = 0;
            try
            {
                if (only_Product != null && only_Product.Length > 0)
                    only_Product_ID = int.Parse(only_Product);
            }
            catch (Exception ex)
            {
                //log.Log(Logging.Level.SEVERE, ex.Message);
            }
            return only_Product_ID;
        }

      

      

        #endregion

    }

}
